<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline label-width="70px">
      <el-form-item :label="t('supply.product_name')">
        <el-input
          v-model="form.product_name"
          clearable
          :placeholder="t('supply.product_name')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('supply.model_id')">
        <el-select
          v-model="form.model_id"
          :filterable="true"
          :placeholder="t('supply.model_id')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in modelList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('supply.seller_id')">
        <el-select
          v-model="form.seller_id"
          :filterable="true"
          :placeholder="t('supply.seller_id')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!--    操作项-->
    <!--    <div class="flex flex-items-center my-5">-->
    <!--      <el-button type="primary" @click="handleAdd('add')">-->
    <!--        {{ t('supply.add') }}-->
    <!--      </el-button>-->
    <!--      <el-button type="danger" :disabled="!multipleSelection.length" @click="handleBatch('delete')">-->
    <!--        {{ t('supply.del') }}-->
    <!--      </el-button>-->
    <!--    </div>-->
    <!-- 表格主体 -->
    <el-table
      :data="dataList"
      highlight-current-row
      stripe
      border
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column :label="t('expandCustomer.serialNumber')" prop="id" min-width="70" />
      <el-table-column
        :label="t('supply.product_name')"
        min-width="200"
        prop="product_name"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('supply.model_id')"
        min-width="200"
        prop="model_name"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('supply.seller_id')"
        min-width="200"
        prop="seller_name"
        :show-overflow-tooltip="true"
      />
      <el-table-column :label="t('system.marketChannel.status')" min-width="250">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            inlinePrompt
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
            @change="handleChangeStatus('single', row)"
          />
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="200">
        <template #default="{ row }">
          <el-button @click="handleJump('edit', row)" size="small">
            {{ t('supply.edit') }}
          </el-button>
          <el-button type="success" @click="handleJump('detail', row)" size="small">
            {{ t('supply.trend') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { delListApi, getGoodsListApi } from '@/api/supply'
import { ElButton } from 'element-plus'
import { getGoodsEnumApi, changeStatusApi } from '@/api/supply'
import { ElMessage, ElMessageBox } from 'element-plus'

const { t } = useI18n()
const { push } = useRouter()

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const paginationTotal = ref<number>(0)
const multipleSelection = ref<any[]>([])

const modelList = ref<Array<Record<string, any>>>([])
const supplierList = ref<Array<Record<string, any>>>([])

const form = ref<Record<string, any>>({
  category: 1,
  seller_id: '',
  model_id: '',
  product_name: '',
  pageIndex: 1,
  pageSize: 15
})

const handleChangeStatus = (type: string, row: Record<string, any>) => {
  ElMessageBox.confirm(
    `是否确认状态流转为${row.status === 1 ? '启用' : '禁用'}？`,
    t('purchase.logistics.tips'),
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const resp = await changeStatusApi({
          ids:
            type === 'single'
              ? [row.id]
              : multipleSelection.value.map((item: Record<string, any>) => item.id),
          status: row.status
        })
        if (resp.code === 0) {
          ElMessage.success(t('market.industryNews.statusMsg'))
          await initialize()
        }
      } catch (e) {
        await initialize()
      }
    })
    .catch(() => {
      row.status = row.status === 1 ? 0 : 1
    })
}

//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getGoodsListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

const handleJump = (type: string, row?: Record<string, any>) => {
  if (type === 'detail') {
    const { startDate, endDate } = getPastYearStartAndEnd()
    push({
      path: '/channelManage/trendManagement',
      query: { model_id: row?.model_id, seller_id: row?.seller_id, startDate, endDate }
    })
  } else {
    push({
      path: `/channelManage/supplier/supplierProductManage/${type}`,
      query: { [(row && 'id') as string]: row?.id }
    })
  }
}

//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

const getPastYearStartAndEnd = () => {
  const today = new Date()

  // 获取一年前的日期，并保持同一时间
  const yearAgo = new Date(today)
  yearAgo.setFullYear(today.getFullYear() - 1)

  // 返回去年同一日期，并将当前时间设置为开始时间
  const startDate = new Date(yearAgo.getTime() + 1000)

  // 将当前时间设置为今天的结束时间
  const endDate = new Date(today)

  return {
    startDate: formatDateWithTime(startDate),
    endDate: formatDateWithTime(endDate)
  }
}
const formatDateWithTime = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day}`
}

const getDropDownBoxInfo = async () => {
  const resp = await getGoodsEnumApi({ field: 'all' })
  modelList.value = resp.data.model
  supplierList.value = resp.data.supplier
}

//重置查询项
const reset = () => {
  form.value = {
    category: 1,
    seller_id: '',
    model_id: '',
    product_name: '',
    pageIndex: 1,
    pageSize: 15
  }
  paginationTotal.value = 0
  initialize()
}

onMounted(() => {
  getDropDownBoxInfo()
  initialize()
})
</script>

<style lang="less" scoped></style>
